<?php

// 读取配置文件
$configs = json_decode(file_get_contents('playlist.json'), true);
if (empty($configs) || empty($configs['channels'])) {
    echo "没有可用的频道配置\n";
    exit(1);
}

// 读取播放列表文件
$playlistContent = file_get_contents('source.txt');
if ($playlistContent === false) {
    echo "无法读取playlist.txt文件\n";
    exit(1);
}

// 解析播放列表，建立频道名称到播放地址的映射
$channelMap = [];
$lines = explode("\n", $playlistContent);
foreach ($lines as $line) {
    $line = trim($line);
    if (empty($line)) continue;

    $parts = explode(',', $line);
    $channelName = trim($parts[1]);
    $playUrl = trim($parts[2]);
    if (str_contains($playUrl, "igmp://")) {
        $playUrl = str_replace("igmp://", "http://192.168.1.40:9999/udp/", $playUrl);
    }
    foreach ($configs['names'] as $name) {
        if (in_array($channelName, $name['from'])) {
            $channelName = $name['to'];
            break;
        }
    }
    $channelMap[$channelName][] = $playUrl;
}


echo "已解析 " . count($channelMap) . " 个频道\n";

// 创建图标目录
if (!is_dir('./icons')) {
    mkdir('./icons', 0755, true);
}

// 生成M3U文件内容
$m3uContent = "#EXTM3U\n";
$txtContent = "";

// 按配置文件的分组和顺序处理频道
foreach ($configs['channels'] as $group) {
    $groupName = $group['group'];
    $channelNames = $group['names'];

    echo "处理分组: {$groupName}\n";

    foreach ($channelNames as $channelName) {
        // 查找频道播放地址
        $playUrls = null;
        if (isset($channelMap[$channelName])) {
            $playUrls = $channelMap[$channelName];
        }
        if ($playUrls) {
            echo "  找到频道: {$channelName}，共 " . count($playUrls) . " 个播放地址\n";
            // 下载频道图标
            $iconDownloaded = downloadChannelIcon($channelName);
            foreach ($playUrls as $playUrl) {
                // 生成M3U条目
                if ($iconDownloaded) {
                    $iconUrl = "https://gitee.com/forsaken2009/jk/raw/main/icons/{$channelName}.png";
                    $m3uContent .= "#EXTINF:-1 tvg-name=\"{$channelName}\" tvg-logo=\"{$iconUrl}\" group-title=\"{$groupName}\",{$channelName}\n";
                } else {
                    $m3uContent .= "#EXTINF:-1 tvg-name=\"{$channelName}\" group-title=\"{$groupName}\",{$channelName}\n";
                }
                $m3uContent .= "{$playUrl}\n";
                $txtContent .= "{$channelName},{$playUrl}\n";
            }
        } else {
            echo "  未找到频道: {$channelName}\n";
        }
    }
}

// 写入M3U文件
file_put_contents('playlist.m3u', $m3uContent);
echo "已生成 playlist.m3u 文件\n";
// 写入TXT文件
file_put_contents('playlist.txt', $txtContent);
echo "已生成 playlist.txt 文件\n";

/**
 * 下载频道图标
 * @param string $channelName 频道名称
 * @return bool 是否下载成功
 */
function downloadChannelIcon($channelName)
{
    $iconPath = "./icons/{$channelName}.png";

    // 如果图标已存在，跳过下载
    if (file_exists($iconPath)) {
        // 查看图片的下载时间
        $lastModified = filemtime($iconPath);
        // 如果超过30天，尝试重新下载
        if (time() - $lastModified > 30 * 24 * 60 * 60) {
            echo "    图标超过30天未修改，尝试重新下载: {$channelName}.png\n";
        } else {
            echo "    图标已存在: {$channelName}.png，上次修改时间: " . date('Y-m-d H:i:s', $lastModified) . "\n";
            return true;
        }
    }

    // 尝试不同的图标名称变体
    $nameVariants = [
        $channelName,                           // 原始名称
        str_replace('-', '', $channelName),     // 去除-字符
        str_replace(' ', '', $channelName),     // 去除空格
        strtolower($channelName),               // 转换为小写
        strtoupper($channelName),                // 转换为大写
        str_replace('4K', '', $channelName),    // 去除4K
    ];
    $nameVariants = array_unique($nameVariants);

    foreach ($nameVariants as $variant) {
        $iconUrl = "https://live.fanmingming.com/tv/{$variant}.png";

        echo "    尝试下载图标: {$iconUrl}\n";

        // 使用curl下载图标
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $iconUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36');

        $imageData = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode === 200 && $imageData !== false && strlen($imageData) > 0) {
            // 验证是否为有效的PNG图片
            if (substr($imageData, 0, 8) === "\x89PNG\r\n\x1a\n") {
                file_put_contents($iconPath, $imageData);
                echo "    图标下载成功: {$channelName}.png\n";
                return true;
            }
        }
    }

    echo "    图标下载失败: {$channelName}\n";
    return false;
}

echo "脚本执行完成\n";
?>